﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SharePoint.Contrib.Diagnostics;

namespace SharePoint.Contrib.Extensions
{
    /// <summary>
    /// Extensions for the Assembly class
    /// </summary>
    public static class AssemblyExtensions
    {

        internal static IEnumerable<Area> FindAllAreas(this Assembly instance)
        {
            var attributes = from attribute in instance.Attributes<DiagnosticsAreaAttribute>()
                             select attribute.Area;

            var areas = from type in instance.GetTypes()
                        where type != typeof(FactoryArea) &&
                              type.IsSubclassOf(typeof(Area))
                        select instance.CreateInstance(type.FullName) as Area;

            return attributes.Concat(areas);

        }

        /// <summary>
        /// Retrieves all attributes of &lt;T&gt; found on the assembly
        /// </summary>
        /// <typeparam name="T">the attribute to locate</typeparam>
        public static IEnumerable<T> Attributes<T>(this Assembly instance)
            where T : Attribute
        {
            var customattributes = Attribute.GetCustomAttributes(instance, typeof(T), false);

            if (customattributes != null)
            {
                foreach (T attribute in customattributes)
                {
                    yield return attribute;
                }
            }
        }
    }
}
